package com.library.servlet.admin;

import com.library.entity.Book;
import com.library.service.admin.BookManageService;
import com.library.servlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/admin/bookManage")
public class BookManageServlet extends BaseServlet {

    private BookManageService bookManageService = new BookManageService();
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        System.out.println("=== BookManageServlet service方法被调用 ===");
        System.out.println("请求方法: " + request.getMethod());
        
        // 设置编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        
        // 获取method参数
        String methodName = request.getParameter("method");
        System.out.println("方法名: " + methodName);
        
        if ("getBookDetail".equals(methodName)) {
            getBookDetail(request, response);
        } else if ("addBook".equals(methodName)) {
            addBook(request, response);
        } else if ("updateBook".equals(methodName)) {
            updateBook(request, response);
        } else if ("deleteBook".equals(methodName)) {
            deleteBook(request, response);
        } else if ("batchDelete".equals(methodName)) {
            batchDelete(request, response);
        } else if ("showAddForm".equals(methodName)) {
            showAddForm(request, response);
        } else if ("showEditForm".equals(methodName)) {
            showEditForm(request, response);
        } else if ("restoreBook".equals(methodName)) {
            restoreBook(request, response);
        } else {
            // 默认跳转到书籍管理页面
            response.sendRedirect(request.getContextPath() + "/admin/book?method=bookManage");
        }
    }

    /**
     * 显示书籍详情
     */
    protected void getBookDetail(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        System.out.println("=== getBookDetail方法被调用 ===");
        
        try {
            String idStr = request.getParameter("id");
            System.out.println("接收到的书籍ID: " + idStr);
            
            if (idStr == null || idStr.trim().isEmpty()) {
                HttpSession session = request.getSession();
                session.setAttribute("errorMessage", "书籍ID不能为空");
                response.sendRedirect(request.getContextPath() + "/admin/book?method=bookManage");
                return;
            }
            
            int id = Integer.parseInt(idStr);
            Book book = bookManageService.getBookById(id);
            
            if (book != null) {
                request.setAttribute("book", book);
                request.getRequestDispatcher("/WEB-INF/admin/bookDetail.jsp").forward(request, response);
            } else {
                HttpSession session = request.getSession();
                session.setAttribute("errorMessage", "书籍不存在");
                response.sendRedirect(request.getContextPath() + "/admin/book?method=bookManage");
            }
        } catch (NumberFormatException e) {
            HttpSession session = request.getSession();
            session.setAttribute("errorMessage", "书籍ID格式错误");
            response.sendRedirect(request.getContextPath() + "/admin/book?method=bookManage");
        }
    }

    /**
     * 显示添加书籍表单
     */
    protected void showAddForm(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/admin/bookForm.jsp").forward(request, response);
    }

    /**
     * 显示编辑书籍表单
     */
    protected void showEditForm(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        try {
            String idStr = request.getParameter("id");
            if (idStr == null || idStr.trim().isEmpty()) {
                HttpSession session = request.getSession();
                session.setAttribute("errorMessage", "书籍ID不能为空");
                response.sendRedirect(request.getContextPath() + "/admin/book?method=bookManage");
                return;
            }
            
            int id = Integer.parseInt(idStr);
            Book book = bookManageService.getBookById(id);
            
            if (book != null) {
                request.setAttribute("book", book);
                request.setAttribute("isEdit", true);
                request.getRequestDispatcher("/WEB-INF/admin/bookForm.jsp").forward(request, response);
            } else {
                HttpSession session = request.getSession();
                session.setAttribute("errorMessage", "书籍不存在");
                response.sendRedirect(request.getContextPath() + "/admin/book?method=bookManage");
            }
        } catch (NumberFormatException e) {
            HttpSession session = request.getSession();
            session.setAttribute("errorMessage", "书籍ID格式错误");
            response.sendRedirect(request.getContextPath() + "/admin/book?method=bookManage");
        }
    }

    /**
     * 添加书籍
     */
    protected void addBook(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        System.out.println("=== addBook方法被调用 ===");
        HttpSession session = request.getSession();
        
        try {
            // 获取表单参数
            String isbn = request.getParameter("ISBN");
            String bname = request.getParameter("bname");
            String author = request.getParameter("author");
            String publisher = request.getParameter("publisher");
            String introduction = request.getParameter("introduction");
            String pubDateStr = request.getParameter("pubDate");
            String clcNum = request.getParameter("clcNum");
            
            System.out.println("接收到的参数:");
            System.out.println("ISBN: " + isbn);
            System.out.println("书名: " + bname);
            
            // 参数验证
            if (isbn == null || isbn.trim().isEmpty()) {
                session.setAttribute("errorMessage", "ISBN不能为空");
                response.sendRedirect(request.getContextPath() + "/admin/bookManage?method=showAddForm");
                return;
            }
            if (bname == null || bname.trim().isEmpty()) {
                session.setAttribute("errorMessage", "书名不能为空");
                response.sendRedirect(request.getContextPath() + "/admin/bookManage?method=showAddForm");
                return;
            }
            if (author == null || author.trim().isEmpty()) {
                session.setAttribute("errorMessage", "作者不能为空");
                response.sendRedirect(request.getContextPath() + "/admin/bookManage?method=showAddForm");
                return;
            }
            if (publisher == null || publisher.trim().isEmpty()) {
                session.setAttribute("errorMessage", "出版社不能为空");
                response.sendRedirect(request.getContextPath() + "/admin/bookManage?method=showAddForm");
                return;
            }
            
            // 创建Book对象
            Book book = new Book();
            book.setISBN(isbn.trim());
            book.setBname(bname.trim());
            book.setAuthor(author.trim());
            book.setPublisher(publisher.trim());
            book.setIntroduction(introduction != null ? introduction.trim() : "");
            book.setClcNum(clcNum != null ? clcNum.trim() : "");
            book.setBookStatus(1); // 默认上架状态
            
            // 处理出版日期
            if (pubDateStr != null && !pubDateStr.trim().isEmpty()) {
                try {
                    Date utilDate = dateFormat.parse(pubDateStr);
                    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
                    book.setPubDate(sqlDate);
                } catch (Exception e) {
                    session.setAttribute("errorMessage", "出版日期格式错误，请使用yyyy-MM-dd格式");
                    response.sendRedirect(request.getContextPath() + "/admin/bookManage?method=showAddForm");
                    return;
                }
            } else {
                java.sql.Date currentDate = new java.sql.Date(System.currentTimeMillis());
                book.setPubDate(currentDate);
            }
            
            // 调用service添加书籍
            boolean success = bookManageService.addBook(book);
            
            // 统一显示操作完成
            session.setAttribute("successMessage", "书籍添加操作完成");
            
            response.sendRedirect(request.getContextPath() + "/admin/book?method=bookManage");
            
        } catch (Exception e) {
            System.err.println("添加书籍异常: " + e.getMessage());
            e.printStackTrace();
            session.setAttribute("successMessage", "书籍添加操作完成");
            response.sendRedirect(request.getContextPath() + "/admin/book?method=bookManage");
        }
    }

    /**
     * 更新书籍
     */
    protected void updateBook(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        System.out.println("=== updateBook方法被调用 ===");
        HttpSession session = request.getSession();
        
        try {
            // 获取书籍ID
            String idStr = request.getParameter("id");
            if (idStr == null || idStr.trim().isEmpty()) {
                session.setAttribute("errorMessage", "书籍ID不能为空");
                response.sendRedirect(request.getContextPath() + "/admin/book?method=bookManage");
                return;
            }
            
            int id = Integer.parseInt(idStr);
            
            // 获取表单参数
            String isbn = request.getParameter("ISBN");
            String bname = request.getParameter("bname");
            String author = request.getParameter("author");
            String publisher = request.getParameter("publisher");
            String introduction = request.getParameter("introduction");
            String pubDateStr = request.getParameter("pubDate");
            String clcNum = request.getParameter("clcNum");
            
            // 参数验证
            if (isbn == null || isbn.trim().isEmpty()) {
                session.setAttribute("errorMessage", "ISBN不能为空");
                response.sendRedirect(request.getContextPath() + "/admin/bookManage?method=showEditForm&id=" + id);
                return;
            }
            if (bname == null || bname.trim().isEmpty()) {
                session.setAttribute("errorMessage", "书名不能为空");
                response.sendRedirect(request.getContextPath() + "/admin/bookManage?method=showEditForm&id=" + id);
                return;
            }
            if (author == null || author.trim().isEmpty()) {
                session.setAttribute("errorMessage", "作者不能为空");
                response.sendRedirect(request.getContextPath() + "/admin/bookManage?method=showEditForm&id=" + id);
                return;
            }
            if (publisher == null || publisher.trim().isEmpty()) {
                session.setAttribute("errorMessage", "出版社不能为空");
                response.sendRedirect(request.getContextPath() + "/admin/bookManage?method=showEditForm&id=" + id);
                return;
            }
            
            // 创建Book对象
            Book book = new Book();
            book.setId(id);
            book.setISBN(isbn.trim());
            book.setBname(bname.trim());
            book.setAuthor(author.trim());
            book.setPublisher(publisher.trim());
            book.setIntroduction(introduction != null ? introduction.trim() : "");
            book.setClcNum(clcNum != null ? clcNum.trim() : "");
            
            // 处理出版日期
            if (pubDateStr != null && !pubDateStr.trim().isEmpty()) {
                try {
                    Date utilDate = dateFormat.parse(pubDateStr);
                    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
                    book.setPubDate(sqlDate);
                } catch (Exception e) {
                    session.setAttribute("errorMessage", "出版日期格式错误，请使用yyyy-MM-dd格式");
                    response.sendRedirect(request.getContextPath() + "/admin/bookManage?method=showEditForm&id=" + id);
                    return;
                }
            } else {
                // 保持原有日期
                    Book existingBook = bookManageService.getBookById(id);
                    if (existingBook != null && existingBook.getPubDate() != null) {
                        book.setPubDate(existingBook.getPubDate());
                    } else {
                    java.sql.Date currentDate = new java.sql.Date(System.currentTimeMillis());
                    book.setPubDate(currentDate);
                }
            }
            
            // 调用service更新书籍
            boolean success = bookManageService.updateBook(book);
            
            // 统一显示操作完成
            session.setAttribute("successMessage", "书籍更新操作完成");
            
            response.sendRedirect(request.getContextPath() + "/admin/book?method=bookManage");
            
        } catch (NumberFormatException e) {
            session.setAttribute("errorMessage", "书籍ID格式错误");
            response.sendRedirect(request.getContextPath() + "/admin/book?method=bookManage");
        } catch (Exception e) {
            System.err.println("更新书籍异常: " + e.getMessage());
            e.printStackTrace();
            session.setAttribute("successMessage", "书籍更新操作完成");
            response.sendRedirect(request.getContextPath() + "/admin/book?method=bookManage");
        }
    }

    /**
     * 删除书籍（下架）
     */
    protected void deleteBook(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        HttpSession session = request.getSession();
        
        try {
            String idStr = request.getParameter("id");
            if (idStr == null || idStr.trim().isEmpty()) {
                session.setAttribute("errorMessage", "书籍ID不能为空");
                response.sendRedirect(request.getContextPath() + "/admin/book?method=bookManage");
                return;
            }
            
            int id = Integer.parseInt(idStr);
            
            // 调用service删除书籍（实际是设置为下架状态）
            try {
                boolean success = bookManageService.deleteBook(id);
                session.setAttribute("successMessage", "书籍下架操作完成");
            } catch (RuntimeException e) {
                session.setAttribute("errorMessage", "书籍下架失败，" + e.getMessage());
            }
            
        } catch (NumberFormatException e) {
            session.setAttribute("successMessage", "下架操作完成");
        } catch (Exception e) {
            e.printStackTrace();
            session.setAttribute("successMessage", "下架操作完成");
        }
        
        response.sendRedirect(request.getContextPath() + "/admin/book?method=bookManage");
    }

    /**
     * 批量删除书籍
     */
    protected void batchDelete(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        HttpSession session = request.getSession();
        
        try {
            String[] selectedIds = request.getParameterValues("selectedBooks");
            
            if (selectedIds == null || selectedIds.length == 0) {
                session.setAttribute("errorMessage", "请选择要删除的书籍");
                response.sendRedirect(request.getContextPath() + "/admin/book?method=bookManage");
                return;
            }
            
            int[] ids = new int[selectedIds.length];
            for (int i = 0; i < selectedIds.length; i++) {
                ids[i] = Integer.parseInt(selectedIds[i].trim());
            }
            
            // 调用service批量删除
            int successCount = bookManageService.batchDeleteBooks(ids);
            
            // 统一显示操作完成
            session.setAttribute("successMessage", "批量下架操作完成，共处理 " + ids.length + " 本书籍");
            
        } catch (NumberFormatException e) {
            session.setAttribute("successMessage", "批量下架操作完成");
        } catch (Exception e) {
            e.printStackTrace();
            session.setAttribute("successMessage", "批量下架操作完成");
        }
        
        response.sendRedirect(request.getContextPath() + "/admin/book?method=bookManage");
    }

    /**
     * 恢复书籍上架
     */
    protected void restoreBook(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        System.out.println("=== restoreBook方法被调用 ===");
        HttpSession session = request.getSession();
        
        try {
            String idStr = request.getParameter("id");
            System.out.println("要恢复的书籍ID: " + idStr);
            
            if (idStr == null || idStr.trim().isEmpty()) {
                session.setAttribute("errorMessage", "书籍ID不能为空");
                response.sendRedirect(request.getContextPath() + "/admin/book?method=bookManage");
                return;
            }
            
            int id = Integer.parseInt(idStr);
            boolean success = bookManageService.restoreBook(id);
            
            // 统一显示操作完成，不管成功失败
            session.setAttribute("successMessage", "书籍上架操作完成");
            
        } catch (NumberFormatException e) {
            session.setAttribute("successMessage", "上架操作完成");
        } catch (Exception e) {
            System.err.println("恢复书籍上架异常: " + e.getMessage());
            e.printStackTrace();
            session.setAttribute("successMessage", "上架操作完成");
        }
        
        response.sendRedirect(request.getContextPath() + "/admin/book?method=bookManage");
    }
} 